<template>
  <div class="addDetail">
    <div class="step-holder">
      <el-steps :active="activeIndex" finish-status="success">
        <el-step title="商品基本信息" />
        <el-step title="添加库存信息" />
        <el-step title="添加移动端详情" />
      </el-steps>
    </div>

    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-form
        ref="addForm"
        size="mini"
        :model="product"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div v-show="activeIndex === 0" class="card-holder step0">
          <!-- 基本信息 -->
          <div class="item">
            <div class="title">基本信息</div>
            <el-row :gutter="20">
              <el-col :span="8" :offset="0">
                <el-form-item label="商品名称" prop="name">
                  <el-input v-model="product.name" />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="商品编码" prop="productSn">
                  <el-input v-model="product.productSn" />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="商品分类" prop="productCategoryId">
                  <el-select
                    v-model="product.productCategoryId"
                    placeholder="商品分类"
                    @change="selectCategory"
                  >
                    <el-option
                      v-for="item in categoryList"
                      :key="item.category.id"
                      :label="item.category.name"
                      :value="item.category.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8" :offset="0">
                <el-form-item label="商品品牌" prop="productBrand">
                  <el-select
                    v-model="product.brandId"
                    placeholder="商品品牌"
                    @change="selectBrand"
                  >
                    <el-option
                      v-for="item in brandList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="16" :offset="0">
                <el-form-item label="商品描述" prop="description">
                  <el-input
                    v-model="product.description"
                    type="textarea"
                    :rows="2"
                    placeholder="描述"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 商品属性 -->
          <div class="item">
            <div class="title">商品属性</div>
            <el-row :gutter="20">
              <el-col :span="8" :offset="0">
                <el-form-item label="商品原价" prop="originalPrice">
                  <el-input-number v-model="product.originalPrice" :min="0" />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="促销类型" prop="promotionType">
                  <el-select
                    v-model="product.promotionType"
                    placeholder="商品品牌"
                    disabled
                  >
                    <el-option
                      v-for="item in promotionList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="活动价格" prop="price">
                  <el-input-number v-model="product.price" disabled :min="0" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8" :offset="0">
                <el-form-item label="重量（kg）" prop="weight">
                  <el-input-number v-model="product.weight" :min="0" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8" :offset="0">
                <el-form-item label="审核状态" prop="verifyStatus">
                  <el-switch
                    v-model="product.verifyStatus"
                    active-value="1"
                    inactive-value="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="是否上架" prop="publishStatus">
                  <el-switch
                    v-model="product.publishStatus"
                    active-value="1"
                    inactive-value="0"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8" :offset="0">
                <el-form-item label="缩略图" prop="img">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="uploadSuccess"
                  >
                    <img v-if="product.pic" :src="product.pic" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon" />
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 其他信息 -->
          <div class="item">
            <div class="title">其他信息</div>
            <el-row :gutter="20">
              <el-col :span="8" :offset="0">
                <el-form-item label="推荐状态" prop="recommendStatus">
                  <el-switch
                    v-model="product.recommendStatus"
                    active-value="1"
                    inactive-value="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="新品状态" prop="newStatus">
                  <el-switch
                    v-model="product.newStatus"
                    active-value="1"
                    inactive-value="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="预告商品" prop="previewStatus">
                  <el-switch
                    v-model="product.previewStatus"
                    active-value="1"
                    inactive-value="0"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8" :offset="0">
                <el-form-item label="搜索关键词" prop="keywords ">
                  <el-input v-model="product.keywords" placeholder="关键词" />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="库存预警" prop="lowStock">
                  <el-input-number v-model="product.lowStock" :min="0" />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="商品排序" prop="sort">
                  <el-input-number v-model="product.sort" :min="0" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="20" :offset="0">
                <el-form-item label="产品服务" prop="service">
                  <el-checkbox-group v-model="serviceChecks">
                    <el-checkbox label="1">无忧退货</el-checkbox>
                    <el-checkbox label="2">快速退款</el-checkbox>
                    <el-checkbox label="3">免费包邮</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div v-show="activeIndex === 1" class="card-holder step0">
          <!-- 基本信息 -->
          <div class="item">
            <div class="title">商品sku信息</div>
            <el-row :gutter="20">
              <el-col :span="8" :offset="0">
                <el-form-item label="标题" prop="subTitle">
                  <el-input v-model="product.subTitle" placeholder="标题" />
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item label="副标题" prop="detailTitle">
                  <el-input
                    v-model="product.detailTitle"
                    placeholder="副标题"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24" :offset="0">
                <!-- 照片墙 -->
                <el-form-item label="画册图片" prop="description">
                  <el-upload
                    ref="photoWall"
                    :limit="5"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :on-success="photoWallUpdateSuccess"
                    :file-list="fileList"
                  >
                    <i class="el-icon-plus" />
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                  只能上传jpg/png文件，且不超过500kb,文件不超过5个
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24" :offset="0">
                <!-- sku生成 -->
                <el-form-item label="sku设置" prop="description">
                  <div
                    v-if="skuObj.color.list.length > 0"
                    class="color checkbox-holder"
                  >
                    颜色：
                    <el-checkbox-group
                      v-model="skuObj.color.checkedList"
                      class="checkbox-box"
                    >
                      <div
                        v-for="(item, index) in skuObj.color.list"
                        :key="index"
                      >
                        <el-checkbox :label="item" />
                        <el-button
                          type="text"
                          size="mini"
                          style="color: red; margin-left: 5px"
                          @click="delColor(index)"
                        >删除</el-button>
                      </div>
                    </el-checkbox-group>
                  </div>
                  <div
                    v-if="skuObj.size.list.length > 0"
                    class="size checkbox-holder"
                  >
                    大小：
                    <el-checkbox-group
                      v-model="skuObj.size.checkedList"
                      class="checkbox-box"
                    >
                      <div
                        v-for="(item, index) in skuObj.size.list"
                        :key="index"
                      >
                        <el-checkbox :label="item" />
                        <el-button
                          type="text"
                          size="mini"
                          style="color: red; margin-left: 5px"
                          @click="delSize(index)"
                        >删除</el-button>
                      </div>
                    </el-checkbox-group>
                  </div>
                  <el-row :gutter="20">
                    <el-col :span="6" :offset="0" style="display: flex">
                      <el-input
                        v-model="skuObj.color.text"
                        size="mini"
                        placeholder="颜色描述：土豪金"
                      />
                      <el-button
                        size="mini"
                        style="margin-left: 10px"
                        @click="addColor"
                      >
                        创建颜色选项
                      </el-button>
                    </el-col>
                    <el-col :span="6" :offset="0" style="display: flex">
                      <el-input
                        v-model="skuObj.size.text"
                        size="mini"
                        placeholder="大小"
                      />
                      <el-button
                        size="mini"
                        style="margin-left: 10px"
                        @click="addSize"
                      >
                        创建大小选项
                      </el-button>
                    </el-col>
                    <el-col :span="8" :offset="0" style="display: flex">
                      <el-button
                        size="mini"
                        type="primary"
                        style="margin-left: 10px"
                        @click="initSkuTable"
                      >
                        生成sku列表
                      </el-button>
                      <el-button
                        size="mini"
                        type="primary"
                        style="margin-left: 10px"
                        @click="addSkuTable"
                      >
                        添加sku
                      </el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="skuList.length > 0" class="table-holder">
              <el-table :data="skuList" border style="width: 100%">
                <el-table-column
                  fixed="left"
                  type="index"
                  label="序号"
                  width="50"
                />
                <el-table-column label="图片" width="150">
                  <template slot-scope="scope">
                    <el-upload
                      class="avatar-uploader"
                      :action="uploadUrl"
                      :headers="uploadHeaders"
                      :show-file-list="false"
                      :on-success="
                        (res, file) => {
                          return tableUploadSuccess(
                            res,
                            file,
                            scope.row.skuCode
                          )
                        }
                      "
                    >
                      <img
                        v-if="scope.row.pic"
                        :src="scope.row.pic"
                        class="avatar"
                      >
                      <i v-else class="el-icon-plus avatar-uploader-icon" />
                    </el-upload>
                  </template>
                </el-table-column>
                <el-table-column label="颜色" width="150">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.spData[0].value"
                      placeholder="请输入颜色"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="大小" width="150">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.spData[1].value"
                      placeholder="请输入大小"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="库存" width="150">
                  <template slot-scope="scope">
                    <el-input
                      v-model.number="scope.row.stock"
                      placeholder="自定义库存"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="预警库存" width="150">
                  <template slot-scope="scope">
                    <el-input
                      v-model.number="scope.row.lowStock"
                      placeholder="自定义预警库存"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="锁定库存" width="150">
                  <template slot-scope="scope">
                    <el-input
                      v-model.number="scope.row.lockStock"
                      placeholder="自定义锁定库存"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="sku编码" width="200">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.skuCode"
                      placeholder="自定义sku编码"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="价格" width="150">
                  <template slot-scope="scope">
                    <el-input
                      v-model.number="scope.row.price"
                      placeholder="自定义价格"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="销量" width="150">
                  <template slot-scope="scope">
                    <el-input
                      v-model.number="scope.row.sale"
                      placeholder="自定义销量"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="default"
                      @click="delSkuTableRow(scope.row.skuCode)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <div v-show="activeIndex === 2" class="card-holder step0">
          商品详情
          <tinymce ref="tinymce" v-model="product.detailHtml" :height="300" />
        </div>
        <div v-if="activeIndex >= 0 && activeIndex <= 2" class="btn-holder">
          <el-button
            v-if="activeIndex > 0"
            size="default"
            @click="prevStep"
          >返回上一步</el-button>
          <el-button type="primary" size="default" @click="nextStep">{{
            nextText
          }}</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  addProduct,
  requestCategoryList,
  requestBrandList,
  requestProductInfo,
  updataProduct
} from '@/api/product'
import mixin from '@/mixins/index'
import { v4 } from 'uuid'
import Tinymce from '@/components/Tinymce'
export default {
  components: { Tinymce },
  mixins: [mixin],
  data() {
    return {
      id: this.$route.params.id,
      skuObj: {
        color: {
          text: '',
          list: [], // 颜色列表
          checkedList: [] // 选中的颜色
        },
        size: {
          text: '',
          list: [], // 大小列表
          checkedList: [] // 选中的大小
        }
      },
      skuList: [], // 拼接好的sku数组
      fileList: [],
      imgList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      // 产品服务多选列表
      serviceChecks: [],
      // 品牌列表
      brandList: [],
      // 分类列表
      categoryList: [],
      // 促销类型
      // 0->没有促销使用原价;1->使用促销价；2->使用会员价；3->使用阶梯价格；4->使用满减价格；5->限时购 ,
      promotionList: [
        { label: '没有促销使用原价', value: 0 },
        { label: '使用促销价', value: 1 },
        { label: '使用会员价', value: 2 },
        { label: '使用阶梯价格', value: 3 },
        { label: '使用满减价格', value: 4 },
        { label: '限时购', value: 5 }
      ],
      // step步数
      activeIndex: 0,
      // sku列表
      pmsSkuStockList: [],
      // 商品信息
      product: {
        originalPrice: 0,
        promotionType: 0,
        price: 0,
        weight: 0,
        verifyStatus: 0,
        publishStatus: 0,
        pic: '',
        recommendStatus: 0,
        newStatus: 0,
        previewStatus: 0,
        lowStock: 0,
        sort: 0
      },
      // 表单验证
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        productSn: [{ required: true, message: '请输入商品编码', trigger: 'blur' }],
        originalPrice: [{ required: true, message: '请输入商品原价', trigger: 'blur' }],
        productCategoryId: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        productBrand: [{ required: true, message: '请选择商品品牌', trigger: 'blur' }],
        subTitle: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        detailTitle: [{ required: true, message: '请输入副标题', trigger: 'blur' }]
      },
      // 上架状态列表
      shelvesStatus: [
        { name: '下架', value: 0 },
        { name: '上架', value: 1 }
      ],
      // 审核状态列表
      examineStatus: [
        { name: '未审核', value: 0 },
        { name: '审核通过', value: 1 }
      ]
    }
  },
  computed: {
    nextText() {
      const arr = ['下一步，填写库存信息', '下一步，填写移动端详情', '提交保存']
      return arr[this.activeIndex]
    }
  },
  created() {
    if (this.id) {
      requestProductInfo(this.id).then(res => {
        console.log(res)
        this.product = res.data.product
        this.skuList = res.data.skus
        this.skuList.forEach(val => {
          val.spData = JSON.parse(val.spData)
        })
        this.skuList.forEach(val => {
          if (val.spData.length === 0) {
            val.spData.push({
              key: '颜色',
              value: ''
            }, {
              key: '大小',
              value: ''
            })
          } else if (val.spData.length === 1) {
            if (val.spData[0].key === '颜色') {
              val.spData.push({
                key: '大小',
                value: ''
              })
            } else if (val.spData[0].key === '大小') {
              val.spData.unshift({
                key: '颜色',
                value: ''
              })
            }
          }
        })
        this.serviceChecks = this.product.serviceIds.split(',')
        // console.log(this.serviceChecks, this.imgList)
      })
    }
    this.getBrandList()
    this.getCategoryList()
  },
  methods: {
    // 删除sku表格行
    delSkuTableRow(skuCode) {
      this.skuList.splice(this.skuList.findIndex(val => val.skuCode === skuCode), 1)
    },
    // 表格上传图片
    tableUploadSuccess(res, file, skuCode) {
      console.log(res, file, skuCode)
      this.skuList.forEach(val => {
        (val.skuCode === skuCode) && (this.$set(val, 'pic', res.data.fileUrl))
      })
    },
    // 删除型号
    delSize(index) {
      this.skuObj.size.list.splice(index, 1)
    },
    // 删除颜色
    delColor(index) {
      this.skuObj.color.list.splice(index, 1)
    },
    // 重置skulist
    resetSkuList() {
      this.skuObj = {
        color: {
          text: '',
          list: [],
          checkedList: []
        },
        size: {
          text: '',
          list: [],
          checkedList: []
        }
      }
    },
    // 遍历sku选项，生成sku列表（笛卡尔积）
    multiDicar() {
      const list = [[...this.skuObj.color.checkedList], [...this.skuObj.size.checkedList]]
      let sku = []
      sku = list.reduce((total, current) => {
        var skuList = []
        total.forEach((out) => {
          current.forEach((inner) => {
            if (typeof out === 'object') {
              skuList.push([...out, inner])
            } else {
              skuList.push([out, inner])
            }
          })
        })
        return skuList
      })
      // console.log(sku)
      return sku
    },
    // 处理sku列表数据
    processingSkuData(arr) {
      const list = []
      arr.forEach(val => {
        list.push({
          skuCode: v4(),
          spData: [{
            key: '颜色',
            value: val[0]
          }, {
            key: '大小',
            value: val[1]
          }]
        })
      })
      console.log(list)
      return list
    },
    // 添加sku
    addSkuTable() {
      if (this.skuObj.color.checkedList.length === 0 && this.skuObj.size.checkedList.length === 0) {
        this.$message.error('选择的sku不能为空')
        return false
      } else if (this.skuObj.color.checkedList.length === 0) {
        this.skuObj.color.checkedList.push('')
      } else if (this.skuObj.size.checkedList.length === 0) {
        this.skuObj.size.checkedList.push('')
      }
      // 笛卡尔积处理sku列表
      const list = this.multiDicar()
      // 转换sku列表的数据格式
      this.skuList.push(...this.processingSkuData(list))
      this.resetSkuList()
    },
    // 生成Sku表格
    initSkuTable() {
      this.skuList = []
      this.addSkuTable()
    },
    // 添加大小
    addSize() {
      this.skuObj.size.list.push(this.skuObj.size.text)
      this.skuObj.size.text = ''
    },
    // 添加颜色
    addColor() {
      this.skuObj.color.list.push(this.skuObj.color.text)
      this.skuObj.color.text = ''
    },
    // 照片墙上传
    photoWallUpdateSuccess(res) {
      this.imgList.push(res.data.fileUrl)
    },
    // 照片墙删除
    handleRemove(file, fileList) {
      const url = file.response.data.fileUrl
      this.imgList.splice(
        this.imgList.findIndex((val) => val === url),
        1
      )
    },
    // 照片墙浏览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 上传图片成功钩子
    uploadSuccess(res) {
      console.log(res)
      if (res.code === 20000) {
        this.product.pic = res.data.fileUrl
      }
    },
    // 分类选择
    selectBrand(e) {
      this.product.brandId = this.brandList[e].id
      this.product.brandName = this.brandList[e].name
      console.log(this.product)
    },
    // 品牌
    selectCategory(e) {
      this.product.productCategoryId = this.categoryList[e].category.id
      this.product.productCategoryName = this.categoryList[e].category.name
      // console.log(this.product)
    },
    // 获取品牌列表
    getBrandList() {
      requestBrandList().then((res) => {
        // console.log(res)
        this.brandList = res.data.items
      })
    },
    // 获取分类列表
    getCategoryList() {
      requestCategoryList().then((res) => {
        // console.log(res)
        this.categoryList = res.data.items
      })
    },
    // 添加商品
    addProductFun() {
      addProduct({ pmsSkuStockList: this.skuList, product: this.product }).then(res => {
        console.log(res)
        if (res.code === 20000) {
          this.$message({
            message: '添加商品成功',
            type: 'success'
          })
          this.$router.go(-1)
        } else {
          this.$message({
            message: '添加商品失败',
            type: 'error'
          })
        }
      })
    },
    // 更新商品
    updataProductFun() {
      updataProduct({ pmsSkuStockList: this.skuList, product: this.product }).then(res => {
        console.log(res)
        if (res.code === 20000) {
          this.$message({
            message: '更新商品成功',
            type: 'success'
          })
          this.$router.go(-1)
        } else {
          this.$message({
            message: '更新商品失败',
            type: 'error'
          })
        }
      })
    },
    // 提交前预处理数据
    initPreUpload() {
      this.skuList.forEach(val => {
        val.spData = JSON.stringify(val.spData)
      })
      this.product.serviceIds = this.serviceChecks.join()
      this.product.albumPics = this.imgList.join()
    },
    // 下一步和添加
    nextStep() {
      if (this.activeIndex === 2) {
        this.initPreUpload()
        if (!this.id) {
          this.addProductFun()
        } else {
          this.updataProductFun()
        }
      } else {
        this.activeIndex++
      }
    },
    // 上一步
    prevStep() {
      this.activeIndex--
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<style lang="scss" scoped>
.addDetail {
  .step-holder {
    width: 100%;
    padding: 30px 300px;
    background-color: #fff;
  }

  .btn-holder {
    display: flex;
    align-self: center;
    justify-content: center;
  }

  .card-holder {
    padding: 20px;

    .title {
      margin-bottom: 30px;
      padding: 10px 0;
      font-size: 16px;
      border-bottom: 1px solid #e5e5e5;
    }
  }

  .checkbox-holder {
    display: flex;
    .checkbox-box {
      display: flex;
    }
  }
}
</style>
